package com.xmy.cultivate.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.JsonNode;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.excelEntity.StaffRankingDetailExcel;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <排位详情>
 * 排位详细 前端控制器
 * </排位详情>
 *
 * @author hpiggy
 * @since 2023-05-16
 */
@RestController
@RequestMapping("/api/staffRankingDetail")
public class StaffRankingDetailController extends BaseController {
    @Autowired
    IStaffRankingDetailService iStaffRankingDetailService;
    @Autowired
    IRoleService iRoleService;
    @Autowired
    IRoleAdminService iRoleAdminService;
    @Autowired
    IStaffService iStaffService;
    @Autowired
    IStaffRankingService iStaffRankingService;

    @PutMapping("/update")
    @ApiOperation("修改排位名次")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "排位详情id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "rankingNum", value = "排位名次", required = false, dataType = "String")
    })
    public Result changeRankingDetail(@RequestBody StaffRankingDetail staffRankingDetail) {
        StaffRankingDetail staffRankingDetail1 = iStaffRankingDetailService.getById(staffRankingDetail.getId());
        if (staffRankingDetail1 == null) {
            return new Result(Code.UPDATE_ERROR, null, "修改失败，该排名详情不存在");
        }

        //排位无法同名次
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("staff_ranking_id", staffRankingDetail.getStaffRankingId());
        wrapper.eq("ranking_num", staffRankingDetail.getRankingNum());
        wrapper.eq("deleted", 0);
        Long count = iStaffRankingDetailService.count(wrapper);
        if (count > 0) {
            return new Result(Code.UPDATE_ERROR, null, "修改失败，该名次已存在");
        }

        staffRankingDetail.setRankingNum(staffRankingDetail.getRankingNum());

        boolean modify = iStaffRankingDetailService.updateById(staffRankingDetail);
        return new Result(modify ? Code.UPDATE_OK : Code.UPDATE_ERROR, null, modify ? Code.UPDATE_OK_MSG : Code.UPDATE_ERROR_MSG);
    }

    @GetMapping("")
    @ApiOperation("排位详情列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "staffName", value = "员工名称", required = false, dataType = "String"),
            @ApiImplicitParam(name = "staffRankingId", value = "排位id", required = false, dataType = "String")
    })
    public Result searchRankingDetail(@RequestParam Map reMap) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        IPage<Staff> page = new Page<>(pageNum, pageSize);

        String roleId = (String) reMap.get("roleId");
        String staffName = (String) reMap.get("staffName");
        String staffRankingId = (String) reMap.get("staffRankingId");

        if (StringUtils.isBlank(staffRankingId)) {
            return new Result(Code.ERROR, "排位id不能为空", "请选择排位");
        }

        QueryWrapper wrapper = new QueryWrapper<>();

        wrapper.eq(StringUtils.isNotBlank(roleId), "role_admin.role_id", roleId);
        wrapper.like(StringUtils.isNotBlank(staffName), "staff_ranking_detail.staff_name", staffName);
        wrapper.eq(StringUtils.isNotBlank(staffRankingId), "staff_ranking_detail.staff_ranking_id", staffRankingId);
        wrapper.eq("staff_ranking_detail.deleted", 0);
        wrapper.orderByAsc("staff_ranking_detail.ranking_num");
        iStaffRankingDetailService.listRankingData(wrapper, page);

        return new Result(Code.GET_OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages()), Code.GET_OK_MSG);
    }

    /**
     * 排位详情进退步列表
     *
     * @param reMap
     * @return
     */
    @GetMapping("/rankings")
    @ApiOperation("排位及工龄")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "rankId1", value = "第一个排位名称", dataType = "String"),
            @ApiImplicitParam(name = "rankId2", value = "第二个排位名称", dataType = "String"),
            @ApiImplicitParam(name = "circumstance", value = "进退步情况", required = false, dataType = "String")
    })
    public Result listQueryRankingDetail(@RequestParam Map reMap) {
        String roleId = (String) reMap.get("roleId");
        String rankId1 = (String) reMap.get("rankId1");
        String rankId2 = (String) reMap.get("rankId2");
        String circumstance = (String) reMap.get("circumstance");
        String teacherId = (String) reMap.get("teacherId");

        QueryWrapper<StaffRankingDetail> queryWrapper = new QueryWrapper<>();
        List rankIdList = new ArrayList<>();

        rankIdList.add(rankId1);
        rankIdList.add(rankId2);

        queryWrapper.eq(StringUtils.isNotBlank(roleId), "role_admin.role_id", roleId).and(wrapper -> rankIdList.forEach(rapper -> wrapper.or(o -> o.eq("staff_ranking_id", rapper))));

        queryWrapper.eq("staff_ranking_detail.deleted", 0);
        queryWrapper.eq("staff_ranking.deleted", 0);
        queryWrapper.eq(StringUtils.isNotBlank(teacherId),"staff_ranking_detail.staff_id", teacherId);
        queryWrapper.orderByDesc("staff_ranking_detail.staff_id");

        List<StaffRankingDetail> list = iStaffRankingDetailService.listStaffRankingDetail(queryWrapper);

        HashMap<String, HashMap<String, Object>> map = new HashMap<>();

        for (StaffRankingDetail staffRankingDetail : list) {
            String staffId = staffRankingDetail.getStaffId().toString();
            HashMap<String, Object> staffData;
            if (map.containsKey(staffId)) {
                staffData = map.get(staffId);
            } else {
                staffData = new HashMap<>();
                staffData.put("teacher", staffRankingDetail.getStaffName());
                staffData.put("rankNum1", 0);
                staffData.put("rankNum2", 0);
                staffData.put("circumstance", 0);
                staffData.put("change", 0);
                map.put(staffId, staffData);
            }
            if (rankId1 != null && !rankId1.equals("") && staffRankingDetail.getStaffRankingId().equals(Long.valueOf(rankId1))) {
                staffData.put("rankNum1", iStaffRankingDetailService.rankingNum(Long.valueOf(rankId1), staffRankingDetail.getStaffId()));
            } else if (rankId2 != null && !rankId1.equals("") && staffRankingDetail.getStaffRankingId().equals(Long.valueOf(rankId2))) {
                staffData.put("rankNum2", iStaffRankingDetailService.rankingNum(Long.valueOf(rankId2), staffRankingDetail.getStaffId()));
            }
        }

        Integer total = 0;

        List<Map<String, Object>> mapList = new ArrayList<>();
        for (HashMap<String, Object> staffData : map.values()) {
            Integer rankNum1 = (Integer) staffData.get("rankNum1");
            Integer rankNum2 = (Integer) staffData.get("rankNum2");
            if (Objects.nonNull(rankNum1) && Objects.nonNull(rankNum2)) {
                if (rankNum1 != 0 && rankNum2 != 0) {
                    Integer rankNum = rankNum1 - rankNum2;
//                    staffData.put("change", Math.abs(rankNum));
                    staffData.put("change", rankNum);
                    if (rankNum >= 0) {
                        staffData.put("circumstance", 0);
                    } else {
                        staffData.put("circumstance", 1);
                    }
                }
            } else {
                staffData.put("change", 0);
                staffData.put("circumstance", 0);
            }
            //进退步条件判断，0默认，1进步，2退步
            if (circumstance.equals("1")) {
                if ((Integer) staffData.get("circumstance") == 0) {
                    mapList.add(staffData);
                    total++;
                }
            } else if (circumstance.equals("2")) {
                if ((Integer) staffData.get("circumstance") == 1) {
                    mapList.add(staffData);
                    total++;
                }
            } else {
                mapList.add(staffData);
                total++;
            }
        }

        HashMap hashMap = new HashMap<>();
        hashMap.put("mapList", mapList);
        hashMap.put("total", total);

        return new Result(Code.GET_OK, hashMap, Code.GET_OK_MSG);
    }

    @GetMapping("/unranked")
    @ApiOperation("未排名的教师列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "staffRankingId", value = "排位id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "roleId", value = "角色id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "staffName", value = "员工名称", required = false, dataType = "String")
    })
    public Result searchTeacher(@RequestParam Map reMap) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        IPage<Staff> page = new Page<>(pageNum, pageSize);

        String staffRankingId = (String) reMap.get("staffRankingId");
        String roleId = (String) reMap.get("roleId");
        String staffName = (String) reMap.get("staffName");
        String rankingNum = (String) reMap.get("rankingNum");

        if (StringUtils.isBlank(staffRankingId)) {
            return new Result(Code.EXP_ERROR, "排位编号不能为空", Code.EXP_MSG);
        }

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("deleted", 0);
        wrapper.like(StringUtils.isNotBlank(staffName), "staff.name", staffName);
        wrapper.ne("staff.`name`", "111");
        wrapper.notLike("staff.name", "前台");
        wrapper.notLike("staff.name", "市场部");
        wrapper.notLike("staff.name", "总部");
        wrapper.eq(StringUtils.isNotBlank(roleId), "role_admin.role_id", roleId);
        wrapper.notExists("(SELECT p.* FROM staff_ranking_detail p WHERE deleted =0 AND staff.id = p.staff_id and staff_ranking_id =" + staffRankingId);

        iStaffService.listCollection(page, wrapper);

        List staffList = new ArrayList<>();
        for (Staff staff : page.getRecords()) {
            HashMap hashMap = new HashMap<>();
            hashMap.put("id", staff.getId());
            hashMap.put("name", staff.getName());
            hashMap.put("rankingNum", "0");
            staffList.add(hashMap);
        }
        return new Result(Code.GET_OK, new PageResult(staffList, page.getTotal(), page.getPages()), Code.GET_OK_MSG);
    }


    @PostMapping("")
    @ApiOperation("批量录入排位详情数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "staffId", value = "员工id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "staffName", value = "员工名称", required = false, dataType = "String"),
            @ApiImplicitParam(name = "staffRankingId", value = "排位id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "rankingNum", value = "排位名次", required = false, dataType = "String")
    })
    public Result createRankingDetail(@RequestBody Map reMap) {
        List<Object> staffList = (List<Object>) reMap.get("staffList");
        String staffRankingId = (String) reMap.get("staffRankingId");

        StringBuilder errorStaffNames = new StringBuilder();
        Integer rightCount = 0;
        Integer errorCount = 0;
        //排位无法同名次
        QueryWrapper wrapper = new QueryWrapper<>();
        List<Map<String, Object>> mapList = new ArrayList<>();

        for (Object object : staffList) {
            String jsonObject = JSON.toJSONString(object);
            StaffRankingDetail staffRankingDetail = JSONObject.parseObject(jsonObject, StaffRankingDetail.class);

            HashMap map = new HashMap<>();
            wrapper.clear();
            wrapper.eq("staff_ranking_id", staffRankingId);
            wrapper.eq("ranking_num", staffRankingDetail.getRankingNum());
            wrapper.eq("deleted", 0);

            Long count = iStaffRankingDetailService.count(wrapper);
            if (count > 0) {
                map.put("staffId", staffRankingDetail.getStaffId());
                map.put("staffName", staffRankingDetail.getStaffName());
                map.put("rankingNum", staffRankingDetail.getRankingNum());
                mapList.add(map);
                errorCount++;
                errorStaffNames.append(staffRankingDetail.getStaffName()).append(",");
            } else {
                StaffRankingDetail detail = new StaffRankingDetail();
                detail.setStaffRankingId(Long.valueOf(staffRankingId));
                detail.setStaffId(staffRankingDetail.getStaffId());
                detail.setStaffName(staffRankingDetail.getStaffName());
                detail.setRankingNum(staffRankingDetail.getRankingNum());
                iStaffRankingDetailService.save(detail);
                rightCount++;
            }
        }

        StringBuilder msgBd = new StringBuilder();
        msgBd.append("成功：").append(rightCount + "条数据");
        if (errorCount > 0) {
            msgBd.append(",");
            msgBd.append("失败：" + errorCount + "条数据");
            msgBd.append(",").append(errorStaffNames).append("该名次已存在");
        }

        return new Result(Code.SAVE_OK, mapList, msgBd.toString());
    }

    /**
     * 批量删除教师排位详情 已作废
     *
     * @param reMap
     * @return
     */
    @ApiOperation("批量删除教师排位详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "idList", value = "排位详情id", required = false, dataType = "String")
    })
    public Result removeRankingDetail(@RequestBody Map reMap) {
        List<Long> idList = (List<Long>) reMap.get("idList");
        for (Long id : idList) {
            StaffRankingDetail staffRankingDetail = iStaffRankingDetailService.getById(id);
            if (staffRankingDetail == null) {
                return new Result(Code.DELETE_ERROR, Code.DELETE_ERROR_MSG, id + "不存在，删除失败~");
            }
        }
        iStaffRankingDetailService.removeByIds(idList);
        return new Result(Code.DELETE_OK, Code.DELETE_OK_MSG, "批量删除成功~");
    }

    @DeleteMapping("/{id}")
    @ApiOperation("单条删除教师排位详情")
    public Result delete(@PathVariable(value = "id") String id) {
        StaffRankingDetail staffRankingDetail = iStaffRankingDetailService.getById(id);
        if (Objects.isNull(staffRankingDetail)) {
            return new Result(Code.EXP_ERROR, Code.EXP_MSG, "该排位详情不存在");
        }
        iStaffRankingDetailService.removeById(Long.parseLong(id));
        return new Result(Code.DELETE_OK, null, "排位详情删除成功~");
    }

}
